package com.jinghangzz.shop.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;

import com.jinghangzz.shop.common.util.ConstatFinalUtil;

/**
 * 专门封装的Http相关的工具类
 * 客户端
 * 
 * jsoup:像js操作html一样,也可以用java操作html;
 * 里面的方法和js的dom方法一模一样;
 * document.getElementById("");
 * 
 * 有专门的成品:HttpComponents;http://hc.apache.org/
 * @author TeaBig
 */
@Component("httpUtil")
public class HttpUtil
{
	/**
	 * get请求
	 * 	实现步骤:
	 * 		搭建一个主流程
	 * 		准备一个url,调用方法,获取响应体(木有请求头,木有请求体,木有响应头)
	 * 		增加请求体
	 * 		增加请求头
	 * 		增加响应体
	 * @param headerMap 请求头
	 * @param parameterMap 请求体
	 * @param responseMap	响应头
	 * @return	服务器提供的响应体
	 */
	public String methodGet(String urlStr,Map<String, String> headerMap,
			Map<String, String> parameterMap,
			Map<String, String> responseMap)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==methodGet==");
		StringBuffer sb = new StringBuffer(); 
		/* 准备工作
		 * 我想拿到管子 */
		InputStream is = null ; 
		OutputStream os = null;  
		try
		{
			/*------get请求需要拼装url------
			 * http://localhost:8080/shop-web-head/index_head.jsp?a=1&b=2&c=3
			 * */
			if(parameterMap.size() > 0 )
			{
				if(!urlStr.endsWith("?"))
				{
					urlStr = urlStr + "?" ; 
				}
				for (Iterator iterator = parameterMap.entrySet().iterator(); iterator.hasNext();)
				{
					Entry me = (Entry) iterator.next();
					String key = me.getKey() + "" ;
					String val = me.getValue() + "" ; 
					urlStr = urlStr + key + "=" + val + "&";
				}
			}
			ConstatFinalUtil.SYS_LOGGER.info("urlStr:{}",urlStr);
			/* 提供一个网址对象 */
			URL url = new URL(urlStr);
			/* 准备管子
			 * 打开一个链接  */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
			
			/* 设置请求头 */
			for (Iterator iterator = headerMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				String val = me.getValue() + "" ; 
				/* 设置请求头 */
				connection.setRequestProperty(key, val);
			}
			
			/* 准备管子 */
			/* OutputStream outputStream = connection.getOutputStream() ; */
			
			/* 输入流 */
			is = connection.getInputStream() ; 
			BufferedReader br = new BufferedReader(new InputStreamReader(is ,"UTF-8"));
			
			String line = "" ; 
			while(( line = br.readLine() ) != null)
			{
				sb.append(line);
			}
			/* 获取响应头 */
			Map<String, List<String>> respoMap = connection.getHeaderFields();
			for (Iterator iterator = respoMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				List<String> valList = (List<String>) me.getValue(); 
				
				StringBuffer valSb = new StringBuffer();
				for (Iterator iterator2 = valList.iterator(); iterator2.hasNext();)
				{
					String temp = (String) iterator2.next();
					valSb.append(temp + "|-->");
				}
				/* 要把响应头放到Map中 */
				responseMap.put(key, valSb.toString());
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("连接服务器出错了;url:{},请求头:{},请求体:{}",
					urlStr,headerMap,parameterMap,e); 
		} finally
		{
			try
			{
				/* 关闭流 */
				if(is != null)
				{
					is.close();  
					is = null ; 
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				/* 关闭流 */
				if(os != null)
				{
					os.close();  
					os = null ; 
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return sb.toString() ; 
	}
	
	/**
	 * get请求
	 * 	实现步骤:
	 * 		搭建一个主流程
	 * 		准备一个url,调用方法,获取响应体(木有请求头,木有请求体,木有响应头)
	 * 		增加请求体
	 * 		增加请求头
	 * 		增加响应体
	 * @param headerMap 请求头
	 * @param parameterMap 请求体
	 * @param responseMap	响应头
	 * @return	服务器提供的响应体
	 */
	public String methodPost(String urlStr,Map<String, String> headerMap,
			Map<String, String> parameterMap,
			Map<String, String> responseMap)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==methodPost==");
		StringBuffer sb = new StringBuffer(); 
		/* 准备工作
		 * 我想拿到管子 */
		InputStream is = null ; 
		OutputStream os = null;  
		try
		{
			//ConstatFinalUtil.SYS_LOGGER.info("urlStr:{}",urlStr);
			/* 提供一个网址对象 */
			URL url = new URL(urlStr);
			/* 准备管子
			 * 打开一个链接  */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
			
			/* 要想设置post提交,
			 * cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
			 *  */
			connection.setDoOutput(true);
			
			/* 设置请求头 */
			for (Iterator iterator = headerMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				String val = me.getValue() + "" ; 
				/* 设置请求头 */
				connection.setRequestProperty(key, val);
			}
			
			StringBuffer reqsb = new StringBuffer();
			/* 拼装请求体 */
			for (Iterator iterator = parameterMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				String val = me.getValue() + "" ; 
				reqsb.append(key + "=" + val + "&");
			}
			//ConstatFinalUtil.SYS_LOGGER.info("请求体:{}",reqsb.toString());
			/* 准备管子 */
			os = connection.getOutputStream() ; 
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			bw.write(reqsb.toString());
			
			bw.flush();
			bw.close();
			
			/* 输入流 */
			is = connection.getInputStream() ; 
			BufferedReader br = new BufferedReader(new InputStreamReader(is ,"UTF-8"));
			
			String line = "" ; 
			while(( line = br.readLine() ) != null)
			{
				sb.append(line);
			}
			/* 获取响应头 */
			Map<String, List<String>> respoMap = connection.getHeaderFields();
			for (Iterator iterator = respoMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				List<String> valList = (List<String>) me.getValue(); 
				
				StringBuffer valSb = new StringBuffer();
				for (Iterator iterator2 = valList.iterator(); iterator2.hasNext();)
				{
					String temp = (String) iterator2.next();
					valSb.append(temp + "|-->");
				}
				/* 要把响应头放到Map中 */
				responseMap.put(key, valSb.toString());
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("连接服务器出错了;url:{},请求头:{},请求体:{}",
					urlStr,headerMap,parameterMap,e); 
		} finally
		{
			try
			{
				/* 关闭流 */
				if(is != null)
				{
					is.close();  
					is = null ; 
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				/* 关闭流 */
				if(os != null)
				{
					os.close();  
					os = null ; 
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return sb.toString() ; 
	}
	
	public static void main(String[] args)
	{
		HttpUtil httpUtil = new HttpUtil();
		String url = "http://localhost:8080/shop-web-head/index_head.jsp" ; 
		/* 请求头
		 * 爬虫:就是用程序模拟浏览器的行为
		 *  */
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("test-a", "1245678");
		headerMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3732.400 QQBrowser/10.5.3824.400");
		/* 请求体 */
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("a", "1");
		parameterMap.put("b", "2");
		parameterMap.put("c", "3");
		parameterMap.put("d", "4");
		/* 响应头 */
		Map<String, String> responseMap = new HashMap<String, String>();
		/* response叫做响应体 */
//		String response = httpUtil.methodGet(url, headerMap, parameterMap, responseMap);
		String response = httpUtil.methodPost(url, headerMap, parameterMap, responseMap);
		System.out.println("--->" + response);
		System.out.println("--响应头->" + responseMap);
	}
}
